<?php

namespace lico\Tool\Apidoc;

class Php
{

    protected $docConfig;

    public function setConfig($config)
    {
        $this->docConfig = $config;
        return $this;
    }

    public function save($apiMap)
    {

        $class = key($apiMap);
        $class = str_replace('app\\controller\\', '', $class);
        $class = strtr($class, '\\', '/');

        $map = current($apiMap);
        $document = [];
        foreach ($map as $k => $comment) {
            $name = $param = $return = '';
            $api = $class . '\\' . $k;
            !empty($comment['name']) && $name = trim($comment['name']);
            !empty($comment['param']) && $param = implode(',', $comment['param']);
            !empty($comment['return']) && $return = current($comment['return']);

            $document[$api] = [$name, $param, $return];
        }

        //头部
        $head = ['接口名', '参数', '返回'];
        array_unshift($document, $head);

        $document = print_r($document, true);
        // p($document);

        $filename = $this->docConfig['fileName'] . '.php';
        $filename = iconv('utf-8', 'gbk', $filename);

        if ($this->docConfig['folder'] && $this->docConfig['folder']{0} == '/') {
            $rootFolder = ROOT_PATH;
        } else {
            $rootFolder = __DIR__ . DS;
        }
        $folder = $rootFolder . ltrim($this->docConfig['folder'], '/');
        // p($folder);
        file_put_contents($folder . $filename, $document);
    }
}
